package com.dnndo.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnndo.common.annotation.DataScope;
import com.dnndo.common.constant.RedisConstant;
import com.dnndo.common.constant.RoleConstants;
import com.dnndo.common.constant.UserConstants;
import com.dnndo.common.core.domain.R;
import com.dnndo.common.core.domain.entity.SysRole;
import com.dnndo.common.core.domain.entity.SysUser;
import com.dnndo.common.core.domain.model.LoginUser;
import com.dnndo.common.core.domain.model.RegisterBodyto;
import com.dnndo.common.core.redis.RedisCache;
import com.dnndo.common.exception.CustomExceptions;
import com.dnndo.common.exception.ServiceException;
import com.dnndo.common.utils.SecurityUtils;
import com.dnndo.common.utils.StringUtils;
import com.dnndo.common.utils.bean.BeanValidators;
import com.dnndo.common.utils.file.FileUploadUtils;
import com.dnndo.common.utils.oss.AliOssUtil;
import com.dnndo.common.utils.spring.SpringUtils;
import com.dnndo.system.domain.SysPost;
import com.dnndo.system.domain.SysUserPost;
import com.dnndo.system.domain.SysUserRole;
import com.dnndo.system.domain.SysUserSchool;
import com.dnndo.system.domain.dto.SchoolDTO;
import com.dnndo.system.domain.dto.SysUserDTO;
import com.dnndo.system.domain.dto.SysUserUpdataAdminsDTO;
import com.dnndo.system.domain.dto.SysUserUpdataMySelfDTO;
import com.dnndo.system.domain.vo.SysUserVO;
import com.dnndo.system.domain.vo.UserDictVO;
import com.dnndo.system.domain.vo.UserInfoVOEN;
import com.dnndo.system.domain.vo.UserInfoVOZH;
import com.dnndo.system.mapper.*;
import com.dnndo.system.service.ISysConfigService;
import com.dnndo.system.service.ISysDeptService;
import com.dnndo.system.service.ISysUserService;
import jakarta.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
  private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
  private static final Long commonRoleId = 119L;
  private static final String info_userName = "info_userName";
  private static final String briefIntroduction = "briefIntroduction";
  private static final String info_avatar = "info_avatar";
  private static final String imagePhoto = "imagePhoto";
  private static final String info_phone = "info_phone";
  private static final String info_schoolName = "info_schoolName";
  private static final String password = "password";
  private final static int SchoolError = -2;
  private static final int PhoneError = -1;
  private static final int Error = 0;


  @Autowired
  private SysUserMapper userMapper;

  @Autowired
  private SysRoleMapper roleMapper;

  @Autowired
  private SysPostMapper postMapper;

  @Autowired
  private SysUserRoleMapper userRoleMapper;

  @Autowired
  private SysUserPostMapper userPostMapper;

  @Autowired
  private ISysConfigService configService;

  @Autowired
  private ISysDeptService deptService;

  @Autowired
  protected Validator validator;

  @Autowired
  protected SysUserMyselfMapper sysUserMyselfMapper;

  @Autowired
  protected SchoolMapper schoolMapper;
  @Autowired
  private AliOssUtil aliOssUtil;
  //rank是校园大使
  private final static Integer ADMIN_RANK = 1;

  //admin的用户id
  private final static Long ADMIN_ADMIN_USER_ID = 1L;

  @Autowired
  protected SysRoleMapper sysRoleMapper;
  @Autowired
  private RedisCache redisCache;

  /**
   * 根据条件分页查询用户列表
   *
   * @return 用户信息集合信息
   */
  @Override
  public List<SysUser> selectUserList(SysUserDTO dto, Long userId) {
    List<String> roleKeys = getUserRoleKeys(userId.intValue());
    //判断当前登陆人是admin
    if (roleKeys.contains("admin")) {
      dto.setRanks(ADMIN_RANK);
      //返回所有学校是校园大使的列表
      return userMapper.selectMySchoolsUserList(dto);
    }
    //调用框架内部方法，获取当前用户角色，一个用户只能有一个角色
    List<Long> roleIds = getUserRole(userId);
    SysUser dtoto = userMapper.selectUserById(userId);

    if (roleIds.size() == 1) {
      //判断当前登陆人是学校管理员
      if (RoleConstants.ROLE_SCHOOL_ADMIN.equals(roleIds.get(0))) {
        dto.setSchoolId(dtoto.getSchoolId());
        //返回在当前学校获得校园大使头衔的用户
        return userMapper.selectMySchoolsUserList(dto);
      }
    } else {
      throw new CustomExceptions("权限错误", 403);
    }
    return null;
  }

  /**
   * 获取指定用户的角色Key集合
   * 逻辑说明：
   * 1. 通过用户ID查询其所有角色。
   * 2. 提取所有角色的roleKey，返回字符串列表。
   *
   * @param userId 用户ID
   * @return List<String> 角色Key列表
   */
  private List<String> getUserRoleKeys(Integer userId) {
    List<SysRole> roles = sysRoleMapper.selectRolePermissionByUserId(userId.longValue());
    return roles.stream().map(SysRole::getRoleKey).toList();
  }


  private List<Long> getUserRole(Long userId) {
    return roleMapper.selectRoleListByUserId(userId);
  }

  @Override
  @DataScope(userAlias = "u")
  public List<SysUser> selectUserList(SysUserDTO dto) {
    //获取登录用户
    LoginUser getLoginUser=SecurityUtils.getLoginUser();
    Long userId = getLoginUser.getUser().getUserId();
    //获取当前用户角色
    List<Long> roleIds = getUserRole(userId);
    //角色只有一个
    if (roleIds.size() == 1) {
      if (RoleConstants.ROLE_SCHOOL_ADMIN.equals(roleIds.get(0))){
        dto.setSchoolId(getLoginUser.getUser().getSchoolId());
      }
    }
    return userMapper.selectUserList(dto);
  }

  /**
   * 根据条件分页查询已分配用户角色列表
   *
   * @param user 用户信息
   * @return 用户信息集合信息
   */
  @Override
  @DataScope(deptAlias = "d", userAlias = "u")
  public List<SysUser> selectAllocatedList(SysUser user) {
    return userMapper.selectAllocatedList(user);
  }

  /**
   * 根据条件分页查询未分配用户角色列表
   *
   * @param user 用户信息
   * @return 用户信息集合信息
   */
  @Override
  @DataScope(deptAlias = "d", userAlias = "u")
  public List<SysUser> selectUnallocatedList(SysUser user) {
    return userMapper.selectUnallocatedList(user);
  }

  /**
   * 通过用户名查询用户
   *
   * @param userName 用户名
   * @return 用户对象信息
   */
  @Override
  public SysUser selectUserByUserName(String userName) {
    // 查询用户信息 查询私有库（默认）
    SysUser sysUser = userMapper.selectUserByUserName(userName);
    if (sysUser != null) {
      //根据用户ID查询用户角色信息 查询私有库（默认）
      List<SysUserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
        .eq(SysUserRole::getUserId, sysUser.getUserId()));
      if (userRoles != null && !userRoles.isEmpty()) {
        //取出userRoles的roleId集合
        List<Long> roleIds = userRoles.stream().map(SysUserRole::getRoleId).toList();
        //根据角色ID查询角色信息 查询公共库
        List<SysRole> roles = roleMapper.selectRoleByIds(roleIds);
        if (!CollectionUtils.isEmpty(roles)) {
          sysUser.setRoles(roles);
        } else {
          throw new CustomExceptions("您没有访问权限", 403);
        }
      }
    }
    return sysUser;
  }

  /**
   * 通过用户ID查询用户
   *
   * @param userId 用户ID
   * @return 用户对象信息
   */
  @Override
  public SysUser selectUserById(Long userId) {
    return userMapper.selectUserById(userId);
  }

  /**
   * 查询用户所属角色组
   *
   * @param userName 用户名
   * @return 结果
   */
  @Override
  public String selectUserRoleGroup(String userName) {
    List<SysRole> list = roleMapper.selectRolesByUserName(userName);
    if (CollectionUtils.isEmpty(list)) {
      return StringUtils.EMPTY;
    }
    return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
  }

  /**
   * 查询用户所属岗位组
   *
   * @param userName 用户名
   * @return 结果
   */
  @Override
  public String selectUserPostGroup(String userName) {
    List<SysPost> list = postMapper.selectPostsByUserName(userName);
    if (CollectionUtils.isEmpty(list)) {
      return StringUtils.EMPTY;
    }
    return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
  }

  /**
   * 校验用户名称是否唯一
   *
   * @param user 用户信息
   * @return 结果
   */
  @Override
  public boolean checkUserNameUnique(SysUser user) {
    Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
    SysUser info = userMapper.checkUserNameUnique(user.getPhonenumber());
    if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
      return UserConstants.NOT_UNIQUE;
    }
    return UserConstants.UNIQUE;
  }

  /**
   * 校验手机号码是否唯一
   *
   * @param user 用户信息
   * @return
   */
  @Override
  public boolean checkPhoneUnique(SysUser user) {
    Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
    SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
    if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
      return UserConstants.NOT_UNIQUE;
    }
    return UserConstants.UNIQUE;
  }

  /**
   * 校验email是否唯一
   *
   * @param user 用户信息
   * @return
   */
  @Override
  public boolean checkEmailUnique(SysUser user) {
    Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
    SysUser info = userMapper.checkEmailUnique(user.getEmail());
    if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
      return UserConstants.NOT_UNIQUE;
    }
    return UserConstants.UNIQUE;
  }

  /**
   * 校验用户是否允许操作
   *
   * @param user 用户信息
   */
  @Override
  public void checkUserAllowed(SysUser user) {
    if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
      throw new ServiceException("不允许操作超级管理员用户");
    }
  }

  /**
   * 校验用户是否有数据权限
   *
   * @param userId 用户id
   */
  @Override
  public void checkUserDataScope(Long userId) {
    List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
    //初始化是否是超级管理员
    boolean isSuperAdmin = false;
    //循环判断是否是超级管理员
    for (SysRole role : roles) {
      if (role.getRoleType().equals(RoleConstants.ROLE_TYPE_SUPER_ADMIN)) {
        isSuperAdmin = true;
        break;
      }
    }
    if (!isSuperAdmin) {
      SysUserDTO user = new SysUserDTO();
      user.setUserId(userId);
      List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
      if (StringUtils.isEmpty(users)) {
        throw new ServiceException("没有权限访问用户数据！");
      }
    }
  }

  /**
   * 新增保存用户信息
   *
   * @param user 用户信息
   * @return 结果
   */
  @Override
  @DSTransactional
  public int insertUser(SysUser user) {
    // 新增用户信息
    int rows = userMapper.insertUser(user);
    // 新增用户岗位关联
    insertUserPost(user);
    // 新增用户与角色管理
    insertUserRole(user);
    return rows;
  }

  /**
   * 注册用户信息
   *
   * @param user 用户信息
   * @return 结果
   */
  @Override
  public boolean registerUser(SysUser user) {
    return userMapper.insertUser(user) > 0;
  }

  /**
   * 修改保存用户信息
   *
   * @param user 用户信息
   * @return 结果
   */
  @Override
  @DSTransactional
  public int updateUser(SysUser user) {
    Long userId = user.getUserId();
    // 删除用户与角色关联
    userRoleMapper.deleteUserRoleByUserId(userId);
    // 新增用户与角色管理
    insertUserRole(user);
    // 删除用户与岗位关联
    userPostMapper.deleteUserPostByUserId(userId);
    // 新增用户与岗位管理
    insertUserPost(user);
    return userMapper.updateUser(user);
  }

  /**
   * 用户授权角色
   *
   * @param userId  用户ID
   * @param roleIds 角色组
   */
  @Override
  @DSTransactional
  public void insertUserAuth(Long userId, Long[] roleIds) {
    userRoleMapper.deleteUserRoleByUserId(userId);
    insertUserRole(userId, roleIds);
  }

  /**
   * 修改用户状态
   *
   * @param user 用户信息
   * @return 结果
   */
  @Override
  public int updateUserStatus(SysUser user) {
    return userMapper.updateUser(user);
  }

  /**
   * 修改用户基本信息
   *
   * @param user 用户信息
   * @return 结果
   */
  @Override
  public int updateUserProfile(SysUser user) {
    return userMapper.updateUser(user);
  }

  /**
   * 修改用户头像
   *
   * @param userName 用户名
   * @param avatar   头像地址
   * @return 结果
   */
  @Override
  public boolean updateUserAvatar(String userName, String avatar) {
    return userMapper.updateUserAvatar(userName, avatar) > 0;
  }

  /**
   * 重置用户密码
   *
   * @param user 用户信息
   * @return 结果
   */
  @Override
  public int resetPwd(SysUser user) {
    return userMapper.updateUser(user);
  }

  /**
   * 重置用户密码
   *
   * @param userName 用户名
   * @param password 密码
   * @return 结果
   */
  @Override
  public int resetUserPwd(String userName, String password) {
    return userMapper.resetUserPwd(userName, password);
  }

  /**
   * 新增用户角色信息
   *
   * @param user 用户对象
   */
  public void insertUserRole(SysUser user) {
    this.insertUserRole(user.getUserId(), user.getRoleIds());
  }

  /**
   * 新增用户岗位信息
   *
   * @param user 用户对象
   */
  public void insertUserPost(SysUser user) {
    Long[] posts = user.getPostIds();
    if (StringUtils.isNotEmpty(posts)) {
      // 新增用户与岗位管理
      List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
      for (Long postId : posts) {
        SysUserPost up = new SysUserPost();
        up.setUserId(user.getUserId());
        up.setPostId(postId);
        list.add(up);
      }
      userPostMapper.batchUserPost(list);
    }
  }

  /**
   * 新增用户角色信息
   *
   * @param userId  用户ID
   * @param roleIds 角色组
   */
  public void insertUserRole(Long userId, Long[] roleIds) {
    if (StringUtils.isNotEmpty(roleIds)) {
      // 新增用户与角色管理
      List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
      for (Long roleId : roleIds) {
        SysUserRole ur = new SysUserRole();
        ur.setUserId(userId);
        ur.setRoleId(roleId);
        list.add(ur);
      }
      userRoleMapper.batchUserRole(list);
    }
  }

  /**
   * 通过用户ID删除用户
   *
   * @param userId 用户ID
   * @return 结果
   */
  @Override
  @DSTransactional
  public int deleteUserById(Long userId) {
    checkUserAllowed(new SysUser(userId));
    checkUserDataScope(userId);
    // 删除用户与角色关联
    userRoleMapper.deleteUserRoleByUserId(userId);
    return userMapper.deleteUserById(userId);
  }

  /**
   * 批量删除用户信息
   *
   * @param userIds 需要删除的用户ID
   * @return 结果
   */
  @Override
  @DSTransactional
  public int deleteUserByIds(Long[] userIds) {
    for (Long userId : userIds) {
      checkUserAllowed(new SysUser(userId));
      checkUserDataScope(userId);
    }
    // 删除用户与角色关联
    userRoleMapper.deleteUserRole(userIds);
    // 删除用户与岗位关联
    userPostMapper.deleteUserPost(userIds);
    return userMapper.deleteUserByIds(userIds);
  }

  /**
   * 导入用户数据
   *
   * @param userList        用户数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName        操作用户
   * @return 结果
   */
  @Override
  public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
    if (StringUtils.isNull(userList) || userList.size() == 0) {
      throw new ServiceException("导入用户数据不能为空！");
    }
    int successNum = 0;
    int failureNum = 0;
    StringBuilder successMsg = new StringBuilder();
    StringBuilder failureMsg = new StringBuilder();
    for (SysUser user : userList) {
      try {
        // 验证是否存在这个用户
        SysUser u = userMapper.selectUserByUserName(user.getUserName());
        if (StringUtils.isNull(u)) {
          BeanValidators.validateWithException(validator, user);
          deptService.checkDeptDataScope(user.getDeptId());
          String password = configService.selectConfigByKey("sys.user.initPassword");
          user.setPassword(SecurityUtils.encryptPassword(password));
          user.setCreateBy(operName);
          userMapper.insertUser(user);
          successNum++;
          successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
        } else if (isUpdateSupport) {
          BeanValidators.validateWithException(validator, user);
          checkUserAllowed(u);
          checkUserDataScope(u.getUserId());
          deptService.checkDeptDataScope(user.getDeptId());
          user.setUserId(u.getUserId());
          user.setUpdateBy(operName);
          userMapper.updateUser(user);
          successNum++;
          successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
        } else {
          failureNum++;
          failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
        }
      } catch (Exception e) {
        failureNum++;
        String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
        failureMsg.append(msg + e.getMessage());
        log.error(msg, e);
      }
    }
    if (failureNum > 0) {
      failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
      throw new ServiceException(failureMsg.toString());
    } else {
      successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
    }
    return successMsg.toString();
  }

  @Override
  public List<UserDictVO> getUserDict() {
    return userMapper.getUserDict();
  }

  /**
   * 更新用户角色信息
   *
   * @param userId
   * @param
   * @return
   */
  @Override
  @Transactional
  public int updateUserRole(Long userId, Long[] roleIds) {
    //删除角色之前的角色信息
    userRoleMapper.deleteUserRoleByUserId(userId);
    // 插入用户新的角色
    SysUserRole userRole = new SysUserRole();

    userRole.setUserId(userId);
    for (Long roleId : roleIds) {
      userRole.setRoleId(roleId);
      userRoleMapper.insert(userRole);
    }
    return 1;
  }

  @Override
  public int updateByIdMDTO(SysUserUpdataMySelfDTO dto) {
    System.out.println("IMPL:updateByIdMDTO:dto = " + dto);
    int i = dto.getTypes().indexOf(dto.getType());
    int row = 0;
    if (i == -1) {
      return row;
    } else {
      if (i == dto.getTypes().indexOf(info_userName)) {
        //修改用户名
        System.out.println("修改用户名");
        row = IupdateNameByIdMDTO(dto);
      } else if (i == dto.getTypes().indexOf(briefIntroduction)) {
        //修改介绍
        System.out.println("修改介绍");
        row = IupdateBriefIntroductionByIdMDTO(dto);
      } else if (i == dto.getTypes().indexOf(info_avatar)) {
        //修改头像
        System.out.println("修改头像");
        row = IupdateAvatarByIdMDTO(dto) ;
      } else if (i == dto.getTypes().indexOf(imagePhoto)) {
        // 修改形象照
        System.out.println("修改形象照");
        row = IupdateImagePhotoByIdMDTO(dto) ;
      }else if (i == dto.getTypes().indexOf(info_phone)) {
        // 修改电话号
        System.out.println("修改电话号");
        row = IupdatePhoneByIdMDTO(dto) ;
      }else if (i == dto.getTypes().indexOf(info_schoolName)) {
        // 修改学校
        System.out.println("修改学校");
        row = IupdateSchoolNameByIdMDTO(dto) ;
      }else if (i == dto.getTypes().indexOf(password)) {
        // 修改密码
        System.out.println("修改密码");
        row = IupdatePasswordByIdMDTO(dto) ;
      }

    }
    return row;
  }

  /**
   * 修改密码
   * @param dto 修改信息
   * @return 修改结果
   */
  private int IupdatePasswordByIdMDTO(SysUserUpdataMySelfDTO dto) {
    //判断密码是否为空
    if (dto.getPassword() != null && dto.getNewPassword() != null || dto.getNewPasswordTwo() != null){
      // 判断旧密码是否正确
      if (SecurityUtils.matchesPassword(dto.getPassword(), SecurityUtils.getLoginUser().getPassword())){
        // 判断新密码两次是否一致
        if (dto.getNewPassword().equals(dto.getNewPasswordTwo())){
          //加密新密码
          dto.setNewPassword(SecurityUtils.encryptPassword(dto.getNewPassword()));
          // 修改密码
          return sysUserMyselfMapper.updatePasswordByIdMDTO(dto);
        }
      }
      return Error;
    }
    return sysUserMyselfMapper.updatePasswordByIdMDTO(dto);
  }

  /**
   * 修改用户学校
   * @param dto 修改信息
   * @return 修改结果
   */
  private int IupdateSchoolNameByIdMDTO(SysUserUpdataMySelfDTO dto) {
    //判断用户学校名称是否为空
    if (dto.getSchoolName() != null || dto.getSchoolNameEn() != null){
      //根据学校名称判断学校是否为空
      SchoolDTO selschoolDTO = new SchoolDTO();
      selschoolDTO.setSchoolName(dto.getSchoolName());
      selschoolDTO.setSchoolNameEn(dto.getSchoolNameEn());
      SchoolDTO schoolDTO = schoolMapper.selectSchoolListByToName(selschoolDTO);
      if (schoolDTO != null){
        dto.setSchoolId(String.valueOf(schoolDTO.getSchoolId()));
        //修改学校名称
        return sysUserMyselfMapper.updateSchoolNameByIdMDTO(dto);
      }
      return SchoolError;
    }else {
      return Error;
    }
  }

  /**
   * 修改电话
   * @param dto 修改信息
   * @return 修改结果
   */
  private int IupdatePhoneByIdMDTO(SysUserUpdataMySelfDTO dto) {
    //判断用户输入电话号是否为空
    if (dto.getPhone() != null){
      //判断电话号是否已被注册
      if (userMapper.selectUserByUserName(dto.getPhone()) != null) {
        return PhoneError;
      }
      //修改电话号
      return sysUserMyselfMapper.updatePhoneByIdMDTO(dto);
    }else {
      return Error;
    }
  }

  /**
   * 修改形象照
   * @param dto 修改信息
   * @return 修改结果
   */
  private int IupdateImagePhotoByIdMDTO(SysUserUpdataMySelfDTO dto) {
    //判断用户上传文件是否为空
    if ( dto.getFiles() != null ){
      //上传文件，获取上传之后的url
      String resultURL = "";
      // 形象照只能上传一个 dto.getFiles().size()恒为1
      for (int i = 0; i < dto.getFiles().size(); i++) {
        System.out.println("i = " + dto.getFiles().get(i));
        //获取文件名
        String fileName = FileUploadUtils.extractFilename(dto.getFiles().get(i));
        //在oss中存储名字
        String objectName = aliOssUtil.getUploadPath() + fileName;
        try {
          resultURL = aliOssUtil.upload(dto.getFiles().get(i).getBytes(), objectName);
        } catch (IOException e) {
          return Error;
        }
      }
      dto.setImagePhoto(resultURL);
      //修改形象照路径
      return sysUserMyselfMapper.updateImagePhotoByIdMDTO(dto);
    }else {
      return Error;
    }


  }

  /**
   * 修改头像
   * @param dto 修改信息
   * @return 修改结果
   */
  private int IupdateAvatarByIdMDTO(SysUserUpdataMySelfDTO dto) {
    //判断用户上传文件是否为空
    if ( dto.getFiles() != null ){
      //上传文件，获取上传之后的url
      String resultURL = "";
      // 头像只能上传一个 dto.getFiles().size()恒为1
      for (int i = 0; i < dto.getFiles().size(); i++) {
        System.out.println("i = " + dto.getFiles().get(i));
        //获取文件名
        String fileName = FileUploadUtils.extractFilename(dto.getFiles().get(i));
        //在oss中存储名字
        String objectName = aliOssUtil.getUploadPath() + fileName;
        try {
          resultURL = aliOssUtil.upload(dto.getFiles().get(i).getBytes(), objectName);
        } catch (IOException e) {
          return Error;
        }
      }
      dto.setAvatar(resultURL);
      //修改头像路径
      return sysUserMyselfMapper.updateAvatarByIdMDTO(dto);
    }else {
      return Error;
    }
    //return sysUserMyselfMapper.updateAvatarByIdMDTO(dto);
  }


  /**
   * 修改简介
   * @param dto 修改信息
   * @return 修改结果
   */
  private int IupdateBriefIntroductionByIdMDTO(SysUserUpdataMySelfDTO dto) {
    //判断用户输入简介是否为空
    if (dto.getBriefIntroduction() != null || dto.getBriefIntroductionEn() != null ){
      //修改简介
      return sysUserMyselfMapper.updateBriefIntroductionByIdMDTO(dto);
    }else {
      return Error;
    }
  }

  /**
   * 修改用户名
   * @param dto 修改信息
   * @return 修改结果
   */
  private int IupdateNameByIdMDTO(SysUserUpdataMySelfDTO dto) {
    //判断用户输入用户名是否为空
    if (dto.getUserName() != null || dto.getUserNameEn() != null){
      //修改的是nick_name
      return sysUserMyselfMapper.updateNameByIdMDTO(dto);
    }else{
      return Error;
    }

  }

  //    根据用户id，查询用户信息中文
  @Override
  public UserInfoVOZH selectUserByIdZh(Integer userId) {
    return userMapper.selectUserByIdZh(userId);
  }

  //    根据用户id，查询用户信息英文
  @Override
  public UserInfoVOEN selectUserByIdEn(Integer userId) {
    return userMapper.selectUserByIdEn(userId);
  }

//注册
  @Override
  public R<String> register(RegisterBodyto user) {
    String cacheObject = redisCache.getCacheObject(RedisConstant.SMS_CODE_KEY + user.getUser_name());
    if (cacheObject != null && cacheObject!=""){
      if (user.getSms_code().equals(cacheObject)){
        if (user.getPassword().equals(user.getPassword_two())) {
          if (user.getUser_name() == null) {
            return R.fail("用户名为空");
          }
          //如果username有重复的 这里其实比对的是数据库的电话号
          if (userMapper.selectUserByUserName(user.getUser_name()) != null) {
            return R.fail("用户名已存在");
          }
          //新增用户
          SysUser sysUser = new SysUser();
          sysUser.setUserName("普通用户");
          sysUser.setNickName("普通用户");
          sysUser.setPhonenumber(user.getUser_name());
          System.out.println("注册接收的密码："+user.getPassword()+"加密之后的密码："+SecurityUtils.encryptPassword(user.getPassword()));
          sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
          sysUser.setStatus("0");
          sysUser.setDelFlag("0");
          sysUser.setCreateBy(user.getPhonenumber());
          sysUser.setRoles(Arrays.asList(new SysRole(2L)));
          sysUser.setCreateTime(new Date());
          int row = userMapper.insertUser(sysUser);
          if (row > 0) {
            // 插入用户角色
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(commonRoleId);
            userRole.setUserId(sysUser.getUserId());
            userRoleMapper.insert(userRole);
            return R.ok("注册成功");
          }
          return R.fail("注册失败");
        }
        return R.ok("两次输入密码不一致");
      }else{
        return R.fail("验证码错误,请重新输入");
      }
    }else{
      return R.fail("验证码过期，请重新请求");
    }

  }


  @Override
  public SysUserSchool selectUserByPhone(String username) {
    return sysUserMyselfMapper.selectUserByPhone(username);
  }

  /**
   * 管理员用户修改个人头像，昵称，简介
   * @param dto
   * @return
   */
  @Override
  public int updateByIdAdmins(SysUserUpdataAdminsDTO dto) {
    return sysUserMyselfMapper.updateByIdAdmins(dto);
  }

  @Override
  public R<SysUserUpdataMySelfDTO> getuserInfoAdmins(Long userId) {
    SysUserUpdataMySelfDTO sysUserUpdataMySelfDTO = sysUserMyselfMapper.getuserInfoAdmins(userId);
    return R.ok(sysUserUpdataMySelfDTO);
  }
}
